<?php

/**
 * @filename Recharge.php
 * @encoding UTF-8
 *
 * @author 徐小军
 *
 * @link http://www.okd100.com
 *
 * @copyright 南昌欧科达科技有效公司
 * @datetime 2016-7-28  9:23:14
 *
 * @version 1.0
 * @Description 充值管理
 */

namespace app\admin\controller;

use app\common\model\User as UserModel;
use app\common\model\CashFlow as CashFlowModel;

class Recharge extends Common
{
    /**
     * 充值记录列表.
     */
    public function showlist()
    {
        if (session('user')->user_type == 'user' or session('user')->user_type == 'agent') {
            return error('没有权限');
        }
        $where = array();
        if ($keyword = input('keyword')) {
            $user = UserModel::where('user_name|user_uniid', 'like', '%'.$keyword.'%')->field('user_id')->select();
            foreach ($user as $u) {
                $user_ids[] = $u['user_id'];
            }
            if ($user_ids) {
                $where['user_id'] = ['in', $user_ids];
            }
        }

        if (input('startdate') && input('enddate')) {
            $startdate = input('startdate');
            $enddate = input('enddate');
            $where['create_time'] = ['>=', $startdate];
            $where['create_time'] = ['<=', $enddate];
        }

        $list = CashFlowModel::where($where)->where('cash_flow_type', 1)->order('create_time DESC')->paginate(getPageSize());
        table_empty_list($list);

        return view('showlist', ['list' => $list, 'startdate' => $startdate, 'enddate' => $enddate, 'keyword' => $keyword]);
    }

    /**
     * 充值
     */
    public function add()
    {
        if (session('user')->user_type == 'user' or session('user')->user_type == 'agent') {
            return error('没有权限');
        }
        try {
            if (IS_POST) {
                $data = input('post.');
                $this->validate_($data, 'Recharge.add');
                $user = session('user');

                $me = UserModel::get($user->user_id);
                $usr = UserModel::where('user_uniid', $data['user_uniid'])->find();
                $me->confirmed_charges()->save(['user_id' => $usr->user_id, 'cash_type' => $data['cash_type'], 'cash_value' => $data['cash_value']]);
                $para = config('msg.send_charged');
                $para['content'] = strtr($para['content'], ['%money_type%' => $data['cash_type'], '%value%' => $data['cash_value']]);
                $usr->mails()->save($para);
                if ($data['cash_value'] > 0) {
                    return success('充值成功');
                } else {
                    return success('操作成功');
                }
            }
        } catch (\Exception $e) {
            return error($e->getMessage());
        }
    }
}
